package com.example.managemyself.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务类
 * 用于发送验证码邮件和密码重置邮件
 */
public class EmailService {
    
    private static final String TAG = "EmailService";
    
    // 邮件配置 - 使用QQ邮箱SMTP
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "587";
    private static final String EMAIL_FROM = "your_email@qq.com"; // 需要配置实际邮箱
    private static final String EMAIL_PASSWORD = "your_app_password"; // QQ邮箱授权码
    
    private static EmailService instance;
    private final ExecutorService executorService;
    private final Handler mainHandler;
    
    private EmailService() {
        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    public static synchronized EmailService getInstance() {
        if (instance == null) {
            instance = new EmailService();
        }
        return instance;
    }
    
    /**
     * 发送验证码邮件
     */
    public void sendVerificationCode(String toEmail, String username, EmailCallback callback) {
        String verificationCode = generateVerificationCode();
        String subject = "ManageMyself - 验证码";
        String content = buildVerificationEmailContent(username, verificationCode);
        
        sendEmail(toEmail, subject, content, new EmailCallback() {
            @Override
            public void onSuccess(String result) {
                // 保存验证码到本地存储，5分钟有效
                saveVerificationCode(toEmail, verificationCode);
                callback.onSuccess(verificationCode);
            }
            
            @Override
            public void onError(String error) {
                callback.onError(error);
            }
        });
    }
    
    /**
     * 发送密码重置成功通知邮件
     */
    public void sendPasswordResetNotification(String toEmail, String username, EmailCallback callback) {
        String subject = "ManageMyself - 密码重置成功";
        String content = buildPasswordResetEmailContent(username);
        
        sendEmail(toEmail, subject, content, callback);
    }
    
    /**
     * 验证验证码
     */
    public boolean verifyCode(String email, String inputCode) {
        String savedCode = getSavedVerificationCode(email);
        if (savedCode != null && savedCode.equals(inputCode)) {
            // 验证成功后删除验证码
            clearVerificationCode(email);
            return true;
        }
        return false;
    }
    
    private void sendEmail(String toEmail, String subject, String content, EmailCallback callback) {
        executorService.execute(() -> {
            try {
                Properties props = new Properties();
                props.put("mail.smtp.host", SMTP_HOST);
                props.put("mail.smtp.port", SMTP_PORT);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.ssl.trust", SMTP_HOST);
                
                Session session = Session.getInstance(props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(EMAIL_FROM, EMAIL_PASSWORD);
                    }
                });
                
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(EMAIL_FROM, "ManageMyself"));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
                message.setSubject(subject);
                message.setContent(content, "text/html; charset=utf-8");
                
                Transport.send(message);
                
                mainHandler.post(() -> callback.onSuccess("邮件发送成功"));
                
            } catch (Exception e) {
                Log.e(TAG, "发送邮件失败", e);
                mainHandler.post(() -> callback.onError("邮件发送失败: " + e.getMessage()));
            }
        });
    }
    
    private String generateVerificationCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }
    
    private String buildVerificationEmailContent(String username, String code) {
        return String.format(
            "<html><body style='font-family: Arial, sans-serif;'>" +
            "<div style='max-width: 600px; margin: 0 auto; padding: 20px;'>" +
            "<h2 style='color: #2196F3;'>ManageMyself 验证码</h2>" +
            "<p>亲爱的 %s，</p>" +
            "<p>您正在进行密码重置操作，您的验证码是：</p>" +
            "<div style='background-color: #f5f5f5; padding: 20px; text-align: center; margin: 20px 0;'>" +
            "<span style='font-size: 32px; font-weight: bold; color: #2196F3; letter-spacing: 5px;'>%s</span>" +
            "</div>" +
            "<p style='color: #666;'>验证码有效期为5分钟，请及时使用。</p>" +
            "<p style='color: #666;'>如果这不是您的操作，请忽略此邮件。</p>" +
            "<hr style='margin: 30px 0; border: none; border-top: 1px solid #eee;'>" +
            "<p style='color: #999; font-size: 12px;'>此邮件由 ManageMyself 系统自动发送，请勿回复。</p>" +
            "</div></body></html>",
            username, code
        );
    }
    
    private String buildPasswordResetEmailContent(String username) {
        return String.format(
            "<html><body style='font-family: Arial, sans-serif;'>" +
            "<div style='max-width: 600px; margin: 0 auto; padding: 20px;'>" +
            "<h2 style='color: #4CAF50;'>密码重置成功</h2>" +
            "<p>亲爱的 %s，</p>" +
            "<p>您的密码已成功重置。</p>" +
            "<p style='color: #666;'>如果这不是您的操作，请立即联系我们。</p>" +
            "<hr style='margin: 30px 0; border: none; border-top: 1px solid #eee;'>" +
            "<p style='color: #999; font-size: 12px;'>此邮件由 ManageMyself 系统自动发送，请勿回复。</p>" +
            "</div></body></html>",
            username
        );
    }
    
    private Context context;
    
    public void setContext(Context context) {
        this.context = context.getApplicationContext();
    }
    
    private void saveVerificationCode(String email, String code) {
        if (context == null) return;
        // 使用SharedPreferences保存验证码，包含时间戳
        android.content.SharedPreferences prefs = 
            context.getSharedPreferences("email_verification", Context.MODE_PRIVATE);
        long expiryTime = System.currentTimeMillis() + 5 * 60 * 1000; // 5分钟后过期
        prefs.edit()
            .putString("code_" + email, code)
            .putLong("expiry_" + email, expiryTime)
            .apply();
    }
    
    private String getSavedVerificationCode(String email) {
        if (context == null) return null;
        android.content.SharedPreferences prefs = 
            context.getSharedPreferences("email_verification", Context.MODE_PRIVATE);
        
        long expiryTime = prefs.getLong("expiry_" + email, 0);
        if (System.currentTimeMillis() > expiryTime) {
            // 验证码已过期
            clearVerificationCode(email);
            return null;
        }
        
        return prefs.getString("code_" + email, null);
    }
    
    private void clearVerificationCode(String email) {
        if (context == null) return;
        android.content.SharedPreferences prefs = 
            context.getSharedPreferences("email_verification", Context.MODE_PRIVATE);
        prefs.edit()
            .remove("code_" + email)
            .remove("expiry_" + email)
            .apply();
    }
    
    public interface EmailCallback {
        void onSuccess(String result);
        void onError(String error);
    }
} 